
var loginModule = angular.module('loginModule', ['Security']);

var INTEGER_REGEXP = /^\-?\d*$/;
loginModule.directive('integer', function() {
return {
	require: 'ngModel',
	link: function(scope, elm, attrs, ctrl) {
		ctrl.$parsers.unshift(function(viewValue) {
		if (INTEGER_REGEXP.test(viewValue)) {
			// it is valid
			ctrl.$setValidity('integer', true);
			return viewValue;
		} else {
			// it is invalid, return undefined (no model update)
			ctrl.$setValidity('integer', false);
			return undefined;
		}
		});
	}
};
});		

loginModule.controller('loginController', ['$location','$scope','$http', '$Security',function($location, $scope, $http, $Security) {				
		$scope.userRegister = function() {
			var userInfo = {
			'username' : $scope.userRegName,
			'password' : $scope.userRegPass,
			'nombre' : $scope.nameReg,				
			'apellido' : $scope.surnameReg,
			'padron' : $scope.padReg,
			'fechaNac' : $scope.birthReg,						
			'email' : $scope.userRegMail,
			'rol' : 0
			};
			$http.post(urlBase + 'securityservice/registeruser', userInfo).success(function(data){
					alert('Usuario creado correctamente. Un mail se ha enviado a la casilla registrada');
				}).error(function(data){
					alert('Hubo un error');					
				}); 
			//$location.path('/home').replace();
			};
		
		$scope.userLogin = function() {
			var userInfo = {
					'username' : $scope.userLoginName,
					'password' : $scope.userLoginPass				
			};
			$http.post(urlBase + 'securityservice/login', userInfo).success(function(data) {
				$scope.response = data;
				if (data.success == false){
					alert(data.reason);
				} else {
					$location.path('/home').replace();
				}
			}).error(function(data){
				alert('Hubo un error en login');					
			}); 	
		}; 
		
		$scope.toggleMock = function(){
			if (urlBase == wsUrl){
				alert('Cambio a mock');
				urlBase = mockUrl;
			} else {
				alert('Cambio a ws');
				urlBase = wsUrl;
			}
			$scope.urlServices = urlBase;
		};
		
		$scope.changePass = function(){
			var passInfo = {
				'oldPassword' : $scope.oldPass,
				'newPassword' : $scope.newPass
			};
			$http.post(wsUrl + 'securityservice/changepassword', passInfo).success(function(data){ // TODO Cambiar a urlBase
				$scope.response = data;
				if (data.success == false){
					alert(data.reason);
				} else {
					alert('Contraseña modificada correctamente');
				}				
			}).error(function(data){
				alert('Hubo un error');					
			}); 			
		};
	}]);
	